<?php
defined( 'BASEPATH' ) or exit( 'No direct script access allowed' );
class Category_model extends MY_Model
{
    private $_category_map = array ();
    private $_category_group = array ();
    function load($gid = null, $exclude_article = false)
    {
        $this->_db->select( $this->_table, '`id`,`fid`,`gid`,`model`,`list_uri`,`content_uri`,`img_cover`,`title`,`subtitle`,`ext`,`sort`' );
        $where = $exclude_article ? '`model`<>0 and `deleted`=0' : '`deleted`=0';
        if (empty( $gid ))
        {
            $this->_db->where( $where );
        }
        else
        {
            $this->_db->where( '`gid`=? and ' . $where, $gid );
        }
        $this->_db->order( '`sort` desc,`id`' );
        if ($data = $this->_db->fetch_all())
        {
            foreach ( $data as &$item )
            {
                $this->_category_map[$item['id']] = &$item;
                $this->_category_group[$item['fid']][] = &$item;
            }
            return ! empty( $this->_category_group );
        }
        return false;
    }
    function get_current($cid)
    {
        if (isset( $this->_category_map[$cid] ))
        {
            return $this->_category_map[$cid];
        }
        return false;
    }
    function get_ids($cid = 0)
    {
        $ids = array ();
        if (empty( $cid ))
        {
            foreach ( $this->_category_group[0] as $item )
            {
                $ids = array_merge( $ids, $this->get_ids( $item['id'] ) );
            }
            if (empty( $ids ))
            {
                $ids[] = 0;
            }
            return $ids;
        }
        $ids[] = $cid;
        if (isset( $this->_category_group[$cid] ))
        {
            foreach ( $this->_category_group[$cid] as $item )
            {
                $ids = array_merge( $ids, $this->get_ids( $item['id'] ) );
            }
        }
        return $ids;
    }
    function get_data()
    {
        return $this->_category_group;
    }
    function get_map()
    {
        return $this->_category_map;
    }
    // 直接访问表
    function get_info_category()
    {
        $this->_db->select( $this->_table, '`id`,`title`' );
        $this->_db->where( '`fid`=0 and `model`=0 and `deleted`=0' );
        return $this->_db->fetch_all();
    }
    function get($id)
    {
        $this->_db->select( $this->_table );
        $this->_db->where( '`id`=? and `deleted`=0', $id );
        $this->_db->limit( 1 );
        return $this->_db->fetch_row();
    }
    function max_gid()
    {
        $this->_db->select( $this->_table, 'max(`gid`)' );
        $this->_db->where( '`deleted`=0' );
        return ( int ) $this->_db->fetch_cell();
    }
    function check_gid($gid)
    {
        $this->_db->select( $this->_table, '`id`' );
        $this->_db->where( '`gid`=? and `fid`=0 and `deleted`=0', $gid );
        $this->_db->limit( 1 );
        return $this->_db->fetch_cell();
    }
}